[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  21. import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  26. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  27. import type { PageModel, PageDocument } from '~/server/models/page';
  28. import type { PageRedirectModel } from '~/server/models/page-redirect';
  29. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  30. import { useEditingMarkdown } from '~/stores/editor';
  31. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  32. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  33. import { useRedirectFrom } from '~/stores/page-redirect';
  34. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  35. import {
  36. useSelectedGrant,
  37. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  38. } from '~/stores/ui';
  39. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  40. import loggerFactory from '~/utils/logger';
  41. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  42. import { BasicLayout } from '../components/Layout/BasicLayout';
  43. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  44. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  45. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  46. import {
  47. useCurrentUser,
  48. useIsLatestRevision,
  49. useIsForbidden, useIsNotFound, useIsSharedUser,
  50. useIsEnabledStaleNotification, useIsIdenticalPath,
  51. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  52. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  53. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  54. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  55. useIsSlackConfigured, useRendererConfig,
  56. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  57. } from '../stores/context';
  58. import { NextPageWithLayout } from './_app.page';
  59. import {
  60. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig,
  61. } from './utils/commons';
  62. declare global {
  63. // eslint-disable-next-line vars-on-top, no-var
  64. var globalEmitter: EventEmitter;
  65. }
  66. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  67. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  68. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  69. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  70. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  71. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  72. const logger = loggerFactory('growi:pages:all');
  73. const {
  74. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  75. } = pagePathUtils;
  76. const { removeHeadingSlash } = pathUtils;
  77. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  78. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  79. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  80. {
  81. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  82. return v?.data != null
  83. && v?.data.toObject != null
  84. && v?.meta != null
  85. && isIPageInfoForEntity(v.meta);
  86. },
  87. serialize: (v) => {
  88. return {
  89. data: superjson.stringify(v.data.toObject()),
  90. meta: superjson.stringify(v.meta),
  91. };
  92. },
  93. deserialize: (v) => {
  94. return {
  95. data: superjson.parse(v.data),
  96. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  97. };
  98. },
  99. },
  100. 'IPageToShowRevisionWithMetaTransformer',
  101. );
  102. // GrowiContextualSubNavigation for NOT shared page
  103. type GrowiContextualSubNavigationProps = {
  104. isLinkSharingDisabled: boolean,
  105. }
  106. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  107. const { isLinkSharingDisabled } = props;
  108. const { data: currentPage } = useSWRxCurrentPage();
  109. return (
  110. <div data-testid="grw-contextual-sub-nav">
  111. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  112. </div>
  113. );
  114. };
  115. const PutbackPageModal = (): JSX.Element => {
  116. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  117. return <PutbackPageModal />;
  118. };
  119. type Props = CommonProps & {
  120. pageWithMeta: IPageToShowRevisionWithMeta | null,
  121. // pageUser?: any,
  122. redirectFrom?: string;
  123. // shareLinkId?: string;
  124. isLatestRevision?: boolean,
  125. isIdenticalPathPage?: boolean,
  126. isForbidden: boolean,
  127. isNotFound: boolean,
  128. isNotCreatable: boolean,
  129. // isAbleToDeleteCompletely: boolean,
  130. templateTagData?: string[],
  131. templateBodyData?: string,
  132. isSearchServiceConfigured: boolean,
  133. isSearchServiceReachable: boolean,
  134. isSearchScopeChildrenAsDefault: boolean,
  135. isSlackConfigured: boolean,
  136. // isMailerSetup: boolean,
  137. isAclEnabled: boolean,
  138. // hasSlackConfig: boolean,
  139. drawioUri: string | null,
  140. hackmdUri: string,
  141. noCdn: string,
  142. // highlightJsStyle: string,
  143. isAllReplyShown: boolean,
  144. isContainerFluid: boolean,
  145. editorConfig: EditorConfig,
  146. isEnabledStaleNotification: boolean,
  147. isEnabledAttachTitleHeader: boolean,
  148. // isEnabledLinebreaks: boolean,
  149. // isEnabledLinebreaksInComments: boolean,
  150. adminPreferredIndentSize: number,
  151. isIndentSizeForced: boolean,
  152. disableLinkSharing: boolean,
  153. grantData?: IPageGrantData,
  154. rendererConfig: RendererConfig,
  155. // UI
  156. userUISettings?: IUserUISettings
  157. // Sidebar
  158. sidebarConfig: ISidebarConfig,
  159. };
  160. const Page: NextPageWithLayout<Props> = (props: Props) => {
  161. // const { t } = useTranslation();
  162. const router = useRouter();
  163. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  164. // register global EventEmitter
  165. if (isClient() && window.globalEmitter == null) {
  166. window.globalEmitter = new EventEmitter();
  167. }
  168. // commons
  169. useEditorConfig(props.editorConfig);
  170. useCsrfToken(props.csrfToken);
  171. // init sidebar config with UserUISettings and sidebarConfig
  172. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  173. // page
  174. useIsLatestRevision(props.isLatestRevision);
  175. useIsContainerFluid(props.isContainerFluid);
  176. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  177. useIsForbidden(props.isForbidden);
  178. useIsNotFound(props.isNotFound);
  179. useIsNotCreatable(props.isNotCreatable);
  180. useRedirectFrom(props.redirectFrom ?? null);
  181. useIsSharedUser(false); // this page cann't be routed for '/share'
  182. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  183. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  184. useIsSearchPage(false);
  185. useTemplateTagData(props.templateTagData);
  186. useTemplateBodyData(props.templateBodyData);
  187. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  188. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  189. useIsSearchServiceReachable(props.isSearchServiceReachable);
  190. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  191. useIsSlackConfigured(props.isSlackConfigured);
  192. // useIsMailerSetup(props.isMailerSetup);
  193. useIsAclEnabled(props.isAclEnabled);
  194. // useHasSlackConfig(props.hasSlackConfig);
  195. useDrawioUri(props.drawioUri);
  196. useHackmdUri(props.hackmdUri);
  197. // useNoCdn(props.noCdn);
  198. useDefaultIndentSize(props.adminPreferredIndentSize);
  199. useIsIndentSizeForced(props.isIndentSizeForced);
  200. useDisableLinkSharing(props.disableLinkSharing);
  201. useRendererConfig(props.rendererConfig);
  202. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  203. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  204. useIsAllReplyShown(props.isAllReplyShown);
  205. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  206. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  207. const { pageWithMeta, userUISettings } = props;
  208. const pageId = pageWithMeta?.data._id;
  209. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  210. const revisionBody = pageWithMeta?.data.revision?.body;
  211. useCurrentPageId(pageId ?? null);
  212. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  213. useRemoteRevisionId(pageWithMeta?.data.revision?._id);
  214. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  215. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  216. useCurrentPathname(props.currentPathname);
  217. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  218. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  219. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  220. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  221. useSetupGlobalSocket();
  222. useSetupGlobalSocketForPage(pageId);
  223. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  224. const shouldRenderPutbackPageModal = pageWithMeta != null
  225. ? _isTrashPage(pageWithMeta.data.path)
  226. : false;
  227. // sync grant data
  228. useEffect(() => {
  229. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  230. mutateSelectedGrant(grantDataToApply);
  231. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  232. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  233. useEffect(() => {
  234. const decodedURI = decodeURI(window.location.pathname);
  235. if (isClient() && decodedURI !== props.currentPathname) {
  236. const { search, hash } = window.location;
  237. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  238. }
  239. }, [props.currentPathname, router]);
  240. // initialize mutateEditingMarkdown only once per page
  241. useEffect(() => {
  242. mutateEditingMarkdown(revisionBody);
  243. }, [mutateEditingMarkdown, revisionBody]);
  244. const title = generateCustomTitleForPage(props, pagePath);
  245. return (
  246. <>
  247. <Head>
  248. <title>{title}</title>
  249. </Head>
  250. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  251. <header className="py-0 position-relative">
  252. <div id="grw-subnav-container">
  253. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  254. </div>
  255. </header>
  256. <div className="d-edit-none">
  257. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  258. </div>
  259. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  260. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  261. <DisplaySwitcher
  262. pageView={
  263. <PageView
  264. pagePath={pagePath}
  265. initialPage={pageWithMeta?.data}
  266. rendererConfig={props.rendererConfig}
  267. />
  268. }
  269. />
  270. <PageStatusAlert />
  271. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  272. </div>
  273. </>
  274. );
  275. };
  276. type LayoutProps = {
  277. children?: ReactNode
  278. className?: string
  279. }
  280. const Layout = ({ children }: LayoutProps): JSX.Element => {
  281. const className = useEditorModeClassName();
  282. return (
  283. <BasicLayout className={className}>
  284. {children}
  285. </BasicLayout>
  286. );
  287. };
  288. Page.getLayout = function getLayout(page) {
  289. return (
  290. <>
  291. <DrawioViewerScript />
  292. <Layout>
  293. {page}
  294. </Layout>
  295. <UnsavedAlertDialog />
  296. <DescendantsPageListModal />
  297. <DrawioModal />
  298. <HandsontableModal />
  299. </>
  300. );
  301. };
  302. function getPageIdFromPathname(currentPathname: string): string | null {
  303. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  304. }
  305. class MultiplePagesHitsError extends ExtensibleCustomError {
  306. pagePath: string;
  307. constructor(pagePath: string) {
  308. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  309. this.pagePath = pagePath;
  310. }
  311. }
  312. // apply parent page grant fot creating page
  313. async function applyGrantToPage(props: Props, ancestor: any) {
  314. await ancestor.populate('grantedGroup');
  315. const grant = {
  316. grant: ancestor.grant,
  317. };
  318. const grantedGroup = ancestor.grantedGroup ? {
  319. grantedGroup: {
  320. id: ancestor.grantedGroup.id,
  321. name: ancestor.grantedGroup.name,
  322. },
  323. } : {};
  324. props.grantData = Object.assign(grant, grantedGroup);
  325. }
  326. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  327. const { model: mongooseModel } = await import('mongoose');
  328. const req: CrowiRequest = context.req as CrowiRequest;
  329. const { crowi } = req;
  330. const { revisionId } = req.query;
  331. const Page = crowi.model('Page') as PageModel;
  332. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  333. const { pageService } = crowi;
  334. let currentPathname = props.currentPathname;
  335. const pageId = getPageIdFromPathname(currentPathname);
  336. const isPermalink = _isPermalink(currentPathname);
  337. const { user } = req;
  338. if (!isPermalink) {
  339. // check redirects
  340. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  341. if (chains != null) {
  342. // overwrite currentPathname
  343. currentPathname = chains.end.toPath;
  344. props.currentPathname = currentPathname;
  345. // set redirectFrom
  346. props.redirectFrom = chains.start.fromPath;
  347. }
  348. // check whether the specified page path hits to multiple pages
  349. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  350. if (count > 1) {
  351. throw new MultiplePagesHitsError(currentPathname);
  352. }
  353. }
  354. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  355. const page = pageWithMeta?.data as unknown as PageDocument;
  356. // add user to seen users
  357. if (page != null && user != null) {
  358. await page.seen(user);
  359. }
  360. // populate & check if the revision is latest
  361. if (page != null) {
  362. page.initLatestRevisionField(revisionId);
  363. await page.populateDataToShowRevision();
  364. props.isLatestRevision = page.isLatestRevision();
  365. }
  366. if (page == null && user != null) {
  367. const templateData = await Page.findTemplate(props.currentPathname);
  368. if (templateData != null) {
  369. props.templateTagData = templateData.templateTags as string[];
  370. props.templateBodyData = templateData.templateBody as string;
  371. }
  372. // apply pagrent page grant
  373. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  374. if (ancestor != null) {
  375. await applyGrantToPage(props, ancestor);
  376. }
  377. }
  378. props.pageWithMeta = pageWithMeta;
  379. }
  380. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  381. const { model: mongooseModel } = await import('mongoose');
  382. const req = context.req as CrowiRequest<IUserHasId & any>;
  383. const { user } = req;
  384. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  385. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  386. if (userUISettings != null) {
  387. props.userUISettings = userUISettings.toObject();
  388. }
  389. }
  390. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  391. const req: CrowiRequest = context.req as CrowiRequest;
  392. const { crowi } = req;
  393. const Page = crowi.model('Page') as PageModel;
  394. const { currentPathname } = props;
  395. const pageId = getPageIdFromPathname(currentPathname);
  396. const isPermalink = _isPermalink(currentPathname);
  397. const page = props.pageWithMeta?.data;
  398. if (props.isIdenticalPathPage) {
  399. props.isNotCreatable = true;
  400. }
  401. else if (page == null) {
  402. props.isNotFound = true;
  403. props.isNotCreatable = !isCreatablePage(currentPathname);
  404. // check the page is forbidden or just does not exist.
  405. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  406. props.isForbidden = count > 0;
  407. }
  408. else {
  409. props.isNotFound = page.isEmpty;
  410. props.isNotCreatable = false;
  411. props.isForbidden = false;
  412. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  413. if (isPermalink && page.isEmpty) {
  414. props.currentPathname = page.path;
  415. }
  416. // /path/to/page ==> /62a88db47fed8b2d94f30000
  417. if (!isPermalink && !page.isEmpty) {
  418. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  419. if (!isToppage) {
  420. props.currentPathname = `/${page._id}`;
  421. }
  422. }
  423. }
  424. }
  425. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  426. // const req: CrowiRequest = context.req as CrowiRequest;
  427. // const { crowi } = req;
  428. // const UserModel = crowi.model('User');
  429. // if (isUserPage(props.currentPagePath)) {
  430. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  431. // if (user != null) {
  432. // props.pageUser = JSON.stringify(user.toObject());
  433. // }
  434. // }
  435. // }
  436. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  437. const req: CrowiRequest = context.req as CrowiRequest;
  438. const { crowi } = req;
  439. const {
  440. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  441. } = crowi;
  442. props.isSearchServiceConfigured = searchService.isConfigured;
  443. props.isSearchServiceReachable = searchService.isReachable;
  444. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  445. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  446. // props.isMailerSetup = mailService.isMailerSetup;
  447. props.isAclEnabled = aclService.isAclEnabled();
  448. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  449. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  450. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  451. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  452. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  453. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  454. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  455. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  456. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  457. props.editorConfig = {
  458. upload: {
  459. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  460. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  461. },
  462. };
  463. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  464. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  465. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  466. props.rendererConfig = {
  467. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  468. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  469. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  470. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  471. plantumlUri: process.env.PLANTUML_URI ?? null,
  472. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  473. // XSS Options
  474. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  475. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  476. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  477. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  478. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  479. };
  480. props.sidebarConfig = {
  481. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  482. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  483. };
  484. }
  485. /**
  486. * for Server Side Translations
  487. * @param context
  488. * @param props
  489. * @param namespacesRequired
  490. */
  491. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  492. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  493. props._nextI18Next = nextI18NextConfig._nextI18Next;
  494. }
  495. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  496. const req = context.req as CrowiRequest<IUserHasId & any>;
  497. const { user } = req;
  498. const result = await getServerSideCommonProps(context);
  499. // check for presence
  500. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  501. if (!('props' in result)) {
  502. throw new Error('invalid getSSP result');
  503. }
  504. const props: Props = result.props as Props;
  505. if (props.redirectDestination != null) {
  506. return {
  507. redirect: {
  508. permanent: false,
  509. destination: props.redirectDestination,
  510. },
  511. };
  512. }
  513. if (user != null) {
  514. props.currentUser = user.toObject();
  515. }
  516. try {
  517. await injectPageData(context, props);
  518. }
  519. catch (err) {
  520. if (err instanceof MultiplePagesHitsError) {
  521. props.isIdenticalPathPage = true;
  522. }
  523. else {
  524. throw err;
  525. }
  526. }
  527. await injectUserUISettings(context, props);
  528. await injectRoutingInformation(context, props);
  529. injectServerConfigurations(context, props);
  530. await injectNextI18NextConfigurations(context, props, ['translation']);
  531. return {
  532. props,
  533. };
  534. };
  535. export default Page;